import {
  fetchGood
} from '../../../../../services/good/fetchGood';
import {
  fetchActivityList
} from '../../../../../services/activity/fetchActivityList';
Component({
  externalClasses: ['custom-class'],

  properties: {
    category: {
      type: Array,
    },
    initActive: {
      type: Array,
      value: [],
      observer(newVal, oldVal) {
        if (newVal[0] !== oldVal[0]) {
          this.setActiveKey(newVal[0], 0);
        }
      },
    },
    isSlotRight: {
      type: Boolean,
      value: false,
    },
    level: {
      type: Number,
      value: 3,
    },
  },
  data: {
    activeKey: 0,
    subActiveKey: 0,
    primaryImage: '',
    specImg: '',
    commentsList: [],
    commentsStatistics: {
      badCount: 0,
      commentCount: 0,
      goodCount: 0,
      goodRate: 0,
      hasImageCount: 0,
      middleCount: 0,
    },
    isShowPromotionPop: false,
    activityList: [],
    details: {},
    goodsTabArray: [{
        name: '商品',
        value: '', // 空字符串代表置顶
      },
      {
        name: '详情',
        value: 'goods-page',
      },
    ],
    storeLogo: '',
    storeName: '云mall标准版旗舰店',
    jumpArray: [{
        title: '首页',
        url: '/pages/home/home',
        iconName: 'home',
      },
      {
        title: '购物车',
        url: '/pages/cart/index',
        iconName: 'cart',
        showCartNum: true,
      },
    ],
    isStock: true,
    cartNum: 0,
    soldout: false,
    buttonType: 1,
    buyNum: 1,
    selectedAttrStr: '',
    skuArray: [],
    primaryImage: '',
    specImg: '',
    isSpuSelectPopupShow: false,
    isCartListPopupShow: false,
    isAllSelectedSku: false,
    buyType: 0,
    outOperateStatus: false, // 是否外层加入购物车
    operateType: 0,
    selectSkuSellsPrice: 0,
    maxLinePrice: 0,
    minSalePrice: 0,
    maxSalePrice: 0,
    list: [],
    spuId: '',
    navigation: {
      type: 'fraction'
    },
    current: 0,
    autoplay: true,
    duration: 500,
    interval: 5000,
    soldNum: 0, // 已售数量
    details: {},
    skuArray: [],
    isStock: true,
    outOperateStatus: false, // 是否外层加入购物车
    storeGoods: [{
      "storeId": "1000",
      "storeName": "云Mall深圳旗舰店",
      "storeStatus": 1,
      "totalDiscountSalePrice": "9990",
      "promotionGoodsList": [{
        "title": "满减满折回归",
        "promotionCode": "MERCHANT",
        "promotionSubCode": "MYJ",
        "promotionId": "159174555838121985",
        "tagText": ["满100元减99.9元"],
        "promotionStatus": 3,
        "tag": "满减",
        "description": "满100元减99.9元,已减99.9元",
        "doorSillRemain": null,
        "isNeedAddOnShop": 0,
        "goodsPromotionList": [{
          "uid": "88888888205468",
          "saasId": "88888888",
          "storeId": "1000",
          "spuId": "12",
          "skuId": "135691622",
          "isSelected": 1,
          "thumb": "https://cdn-we-retail.ym.tencent.com/tsr/goods/dz-3a.png",
          "title": "腾讯极光盒子",
          "primaryImage": "https://cdn-we-retail.ym.tencent.com/tsr/goods/dz-3a.png",
          "quantity": 1,
          "stockStatus": true,
          "stockQuantity": 3,
          "price": "9900",
          "originPrice": "16900",
          "tagPrice": null,
          "titlePrefixTags": [{
            "text": "新品"
          }, {
            "text": "火爆"
          }],
          "roomId": null,
          "specInfo": [{
            "specTitle": "颜色",
            "specValue": "经典白"
          }, {
            "specTitle": "类型",
            "specValue": "经典套装"
          }],
          "joinCartTime": "2020-06-29T07:55:40.000+0000",
          "available": 1,
          "putOnSale": 1,
          "etitle": null
        }, {
          "uid": "88888888205468",
          "saasId": "88888888",
          "storeId": "1000",
          "spuId": "18",
          "skuId": "135681631",
          "isSelected": 1,
          "thumb": "https://cdn-we-retail.ym.tencent.com/tsr/goods/nz-09a.png",
          "title": "白色短袖连衣裙荷叶边裙摆宽松韩版休闲纯白清爽优雅连衣裙",
          "primaryImage": "https://cdn-we-retail.ym.tencent.com/tsr/goods/nz-09a.png",
          "quantity": 1,
          "stockStatus": true,
          "stockQuantity": 177,
          "price": "29800",
          "originPrice": "40000",
          "tagPrice": null,
          "titlePrefixTags": null,
          "roomId": null,
          "specInfo": [{
            "specTitle": "颜色",
            "specValue": "米色荷叶边"
          }, {
            "specTitle": "尺码",
            "specValue": "M"
          }],
          "joinCartTime": "2020-06-29T07:55:27.000+0000",
          "available": 1,
          "putOnSale": 1,
          "etitle": null
        }, {
          "uid": "88888888205468",
          "saasId": "88888888",
          "storeId": "1000",
          "spuId": "13",
          "skuId": "135698362",
          "isSelected": 1,
          "thumb": "https://cdn-we-retail.ym.tencent.com/tsr/goods/muy-3a.png",
          "title": "带帽午休毯虎年款多功能加厚加大加绒简约多功能午休毯连帽披肩",
          "primaryImage": "https://cdn-we-retail.ym.tencent.com/tsr/goods/muy-3a.png",
          "quantity": 13,
          "stockStatus": true,
          "stockQuantity": 9,
          "price": "29900",
          "originPrice": "0",
          "tagPrice": null,
          "titlePrefixTags": [{
            "text": "火爆"
          }],
          "roomId": null,
          "specInfo": [{
            "specTitle": "颜色",
            "specValue": "浅灰色"
          }, {
            "specTitle": "尺码",
            "specValue": "M"
          }],
          "joinCartTime": "2020-06-29T07:54:43.000+0000",
          "available": 1,
          "putOnSale": 1,
          "etitle": null
        }, {
          "uid": "88888888205468",
          "saasId": "88888888",
          "storeId": "1000",
          "spuId": "7",
          "skuId": "135681625",
          "isSelected": 1,
          "thumb": "https://cdn-we-retail.ym.tencent.com/tsr/goods/gh-2b.png",
          "title": "不锈钢刀叉勺套装家用西餐餐具ins简约耐用不锈钢金色银色可选",
          "primaryImage": "https://cdn-we-retail.ym.tencent.com/tsr/goods/gh-2b.png",
          "quantity": 1,
          "stockStatus": true,
          "stockQuantity": 0,
          "price": "29900",
          "originPrice": "29900",
          "tagPrice": null,
          "titlePrefixTags": null,
          "roomId": null,
          "specInfo": [{
            "specTitle": "颜色",
            "specValue": "奶黄色"
          }, {
            "specTitle": "数量",
            "specValue": "六件套"
          }],
          "joinCartTime": "2020-06-29T07:55:00.000+0000",
          "available": 1,
          "putOnSale": 1,
          "etitle": null
        }],
        "lastJoinTime": "2020-06-29T07:55:40.000+0000"
      }, {
        "title": null,
        "promotionCode": "EMPTY_PROMOTION",
        "promotionSubCode": null,
        "promotionId": null,
        "tagText": null,
        "promotionStatus": null,
        "tag": null,
        "description": null,
        "doorSillRemain": null,
        "isNeedAddOnShop": 0,
        "goodsPromotionList": [{
          "uid": "88888888205468",
          "saasId": "88888888",
          "storeId": "1000",
          "spuId": "11",
          "skuId": "135691629",
          "isSelected": 0,
          "thumb": "https://cdn-we-retail.ym.tencent.com/tsr/goods/nz-17a.png",
          "title": "运动连帽拉链卫衣休闲开衫长袖多色运动细绒面料运动上衣",
          "primaryImage": "https://cdn-we-retail.ym.tencent.com/tsr/goods/nz-17a.png",
          "quantity": 1,
          "stockStatus": false,
          "stockQuantity": 0,
          "price": "25900",
          "originPrice": "39900",
          "tagPrice": null,
          "tagText": null,
          "roomId": null,
          "specInfo": [{
            "specTitle": "颜色",
            "specValue": "军绿色"
          }, {
            "specTitle": "尺码",
            "specValue": "S"
          }],
          "joinCartTime": "2020-04-24T06:26:48.000+0000",
          "available": 1,
          "putOnSale": 1,
          "etitle": null
        }, {
          "uid": "88888888205468",
          "saasId": "88888888",
          "storeId": "1000",
          "spuId": "5",
          "skuId": "135691635",
          "isSelected": 0,
          "thumb": "https://cdn-we-retail.ym.tencent.com/tsr/goods/dz-2a.png",
          "title": "迷你便携高颜值蓝牙无线耳机立体声只能触控式操作简约立体声耳机",
          "primaryImage": "https://cdn-we-retail.ym.tencent.com/tsr/goods/dz-2a.png",
          "quantity": 1,
          "stockStatus": true,
          "stockQuantity": 96,
          "price": "29000",
          "originPrice": "29900",
          "tagPrice": null,
          "tagText": null,
          "roomId": null,
          "specInfo": [{
            "specTitle": "颜色",
            "specValue": "黑色"
          }, {
            "specTitle": "类型",
            "specValue": "简约款"
          }],
          "joinCartTime": "2020-06-29T07:55:17.000+0000",
          "available": 1,
          "putOnSale": 1,
          "etitle": null
        }],
        "lastJoinTime": null
      }],
      "lastJoinTime": "2020-06-29T07:55:40.000+0000",
      "postageFreePromotionVo": {
        "title": null,
        "promotionCode": null,
        "promotionSubCode": null,
        "promotionId": null,
        "tagText": null,
        "promotionStatus": null,
        "tag": null,
        "description": null,
        "doorSillRemain": null,
        "isNeedAddOnShop": 0
      }
    }]
  },
  attached() {
    if (this.properties.initActive && this.properties.initActive.length > 0) {
      this.setData({
        activeKey: this.properties.initActive[0],
        subActiveKey: this.properties.initActive[1] || 0,
      });
    }
  },
  methods: {
    handlePopupHide() {
      this.setData({
        isCartListPopupShow: false,
        isSpuSelectPopupShow: false,
      });
    },
    //购物车弹框
    showCartGroupList() {
      this.setData({
        isCartListPopupShow: true
      })
    },
    selectSpecsName(selectSpecsName) {
      if (selectSpecsName) {
        this.setData({
          selectedAttrStr: selectSpecsName,
        });
      } else {
        this.setData({
          selectedAttrStr: '',
        });
      }
    },
    showSkuSelectPopup(type) {
      this.setData({
        buyType: type || 0,
        outOperateStatus: type >= 1,
        isSpuSelectPopupShow: true,
      });
    },
    chooseSpecItem(e) {
      const {
        specList
      } = this.data.details;
      const {
        selectedSku,
        isAllSelectedSku
      } = e.detail;
      if (!isAllSelectedSku) {
        this.setData({
          selectSkuSellsPrice: 0,
        });
      }
      this.setData({
        isAllSelectedSku,
      });
      this.getSkuItem(specList, selectedSku);
    },

    getSkuItem(specList, selectedSku) {
      const {
        skuArray,
        primaryImage
      } = this.data;
      const selectedSkuValues = this.getSelectedSkuValues(specList, selectedSku);
      let selectedAttrStr = ` 件  `;
      selectedSkuValues.forEach((item) => {
        selectedAttrStr += `，${item.specValue}  `;
      });
      // eslint-disable-next-line array-callback-return
      const skuItem = skuArray.filter((item) => {
        let status = true;
        (item.specInfo || []).forEach((subItem) => {
          if (
            !selectedSku[subItem.specId] ||
            selectedSku[subItem.specId] !== subItem.specValueId
          ) {
            status = false;
          }
        });
        if (status) return item;
      });
      this.selectSpecsName(selectedSkuValues.length > 0 ? selectedAttrStr : '');
      if (skuItem) {
        this.setData({
          selectItem: skuItem,
          selectSkuSellsPrice: skuItem.price || 0,
        });
      } else {
        this.setData({
          selectItem: null,
          selectSkuSellsPrice: 0,
        });
      }
      this.setData({
        specImg: skuItem && skuItem.skuImage ? skuItem.skuImage : primaryImage,
      });
    },
    // 获取已选择的sku名称
    getSelectedSkuValues(skuTree, selectedSku) {
      const normalizedTree = this.normalizeSkuTree(skuTree);
      return Object.keys(selectedSku).reduce((selectedValues, skuKeyStr) => {
        const skuValues = normalizedTree[skuKeyStr];
        const skuValueId = selectedSku[skuKeyStr];
        if (skuValueId !== '') {
          const skuValue = skuValues.filter((value) => {
            return value.specValueId === skuValueId;
          })[0];
          skuValue && selectedValues.push(skuValue);
        }
        return selectedValues;
      }, []);
    },

    normalizeSkuTree(skuTree) {
      const normalizedTree = {};
      skuTree.forEach((treeItem) => {
        normalizedTree[treeItem.specId] = treeItem.specValueList;
      });
      return normalizedTree;
    },
    changeNum(e) {
      this.setData({
        buyNum: e.detail.buyNum,
      });
    },
    specsConfirm() {
      const {
        buyType
      } = this.data;
      if (buyType === 1) {
        this.gotoBuy();
      } else {
        this.addCart();
      }
      // this.handlePopupHide();
    },

    addCart() {
      const {
        isAllSelectedSku
      } = this.data;
      Toast({
        context: this,
        selector: '#t-toast',
        message: isAllSelectedSku ? '点击加入购物车' : '请选择规格',
        icon: '',
        duration: 1000,
      });
    },

    gotoBuy(type) {
      const {
        isAllSelectedSku,
        buyNum
      } = this.data;
      if (!isAllSelectedSku) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '请选择规格',
          icon: '',
          duration: 1000,
        });
        return;
      }
      this.handlePopupHide();
      const query = {
        quantity: buyNum,
        storeId: '1',
        spuId: this.data.spuId,
        goodsName: this.data.details.title,
        skuId: type === 1 ? this.data.skuList[0].skuId : this.data.selectItem.skuId,
      };
      let urlQueryStr = obj2Params({
        goodsRequestList: JSON.stringify([query]),
      });
      urlQueryStr = urlQueryStr ? `?${urlQueryStr}` : '';
      const path = `/pages/order/order-confirm/index${urlQueryStr}`;
      wx.navigateTo({
        url: path,
      });
    },
    onParentChange(event) {
      this.setActiveKey(event.detail.index, 0).then(() => {
        this.triggerEvent('change', [
          this.data.activeKey,
          this.data.subActiveKey,
        ]);
      });
    },
    onChildChange(event) {
      this.setActiveKey(this.data.activeKey, event.detail.index).then(() => {
        this.triggerEvent('change', [
          this.data.activeKey,
          this.data.subActiveKey,
        ]);
      });
    },
    onIconTap() {
      console.log('点击了加号')

    },
    onSelectTap() {
      this.getDetail(3)
      this.showSkuSelectPopup(2)
      console.log('点击了选择')
    },
    goodsDetail(e) {
      console.log(e)
      const spuId = 3
      wx.navigateTo({
        url: `/pages/goods/details/index?spuId=${spuId}`,
      });
    },
    getDetail(spuId) {
      Promise.all([fetchGood(spuId), fetchActivityList()]).then((res) => {

        const [details, activityList] = res;
        const skuArray = [];
        const {
          skuList,
          primaryImage,
          isPutOnSale,
          minSalePrice,
          maxSalePrice,
          maxLinePrice,
          soldNum,
        } = details;
        skuList.forEach((item) => {
          skuArray.push({
            skuId: item.skuId,
            quantity: item.stockInfo ? item.stockInfo.stockQuantity : 0,
            specInfo: item.specInfo,
          });
        });
        const promotionArray = [];
        activityList.forEach((item) => {
          promotionArray.push({
            tag: item.promotionSubCode === 'MYJ' ? '满减' : '满折',
            label: '满100元减99.9元',
          });
        });
        this.setData({
          details,
          activityList,
          isStock: details.spuStockQuantity > 0,
          maxSalePrice: maxSalePrice ? parseInt(maxSalePrice) : 0,
          maxLinePrice: maxLinePrice ? parseInt(maxLinePrice) : 0,
          minSalePrice: minSalePrice ? parseInt(minSalePrice) : 0,
          list: promotionArray,
          skuArray: skuArray,
          primaryImage,
          soldout: isPutOnSale === 0,
          soldNum,
        });
      });
    },
    changCategory(event) {
      const {
        item
      } = event.currentTarget.dataset;
      this.triggerEvent('changeCategory', {
        item,
      });
    },
    setActiveKey(key, subKey) {
      return new Promise((resolve) => {
        this.setData({
            activeKey: key,
            subActiveKey: subKey,
          },
          () => {
            resolve();
          },
        );
      });
    },
  },
});